﻿Imports USA411
Imports LabJack.LabJackUD.U3
Imports System.Data
Imports System.Data.SqlClient
Imports USA411.U3Config
Imports System.Text
Imports System.IO

Module mdlMail
    Friend EditDevice As Integer
    Friend EditPort As Integer
    Friend EditAction As Integer

    Friend HS2Connect As New DataSet

    Friend U3Cfg As DataSet()
    Friend Actions As New DataSet

    Friend pNumFound As Integer
    Friend pSerialNumbers As Integer()
    Friend pIDs As Integer()
    Friend pAddresses As Double()
    Friend ihandle As Integer()

    Friend a1 As New DataTable
    Friend a2 As New DataTable
    Friend a3 As New DataTable

    Friend App_Dir As String = Directory.GetCurrentDirectory & "\..\..\.\"

    Friend Sub LoadUpU3s()
        HS2Connect.ReadXml("HS2Connect.XML")
        ReDim pSerialNumbers(128)
        ReDim pIDs(128)
        ReDim pAddresses(128)
        For x As Integer = 0 To 128
            pSerialNumbers(x) = 0
            pIDs(x) = 0
            pAddresses(x) = 0
        Next
        ListAll(DEVICE.U3, CONNECTION.USB, pNumFound, pSerialNumbers, pIDs, pAddresses)
        ReDim ihandle(pNumFound - 1)
        ReDim Preserve pSerialNumbers(pNumFound - 1)
        ReDim U3Cfg(pNumFound - 1)
        For iloop As Int16 = 0 To ihandle.Length - 1
            OpenLabJack(DEVICE.U3, CONNECTION.USB, pSerialNumbers(iloop), False, ihandle(iloop))
            ' ComboBox1.Items.Add(pSerialNumbers(iloop))
            U3Cfg(iloop) = ReadOrMakeXML(pSerialNumbers(iloop))
        Next
        Actions.ReadXml(App_Dir & "Actions.xml")
        a1 = Actions.Tables(0).Copy
        a2 = Actions.Tables(0).Copy
        a3 = Actions.Tables(0).Copy
    End Sub

    Friend Sub WritePorts()
        'todo Add Write Code here
        U3Cfg(EditDevice).WriteXml(U3Cfg(EditDevice).Tables(0).Rows(0).Item("DeviceID") & ".XML")
    End Sub

    Friend Sub WriteActions()
        Actions.WriteXml(App_Dir & "Actions.xml")


        a1 = Actions.Tables(0).Copy
        a2 = Actions.Tables(0).Copy
        a3 = Actions.Tables(0).Copy

    End Sub

    Private Function ReadOrMakeXML(ByVal FileName As String) As DataSet
        Dim ds As New DataSet
        Try
            ds.ReadXml(App_Dir & FileName & ".xml")
        Catch ex As Exception
            ds.ReadXml(App_Dir & "0.xml")
            For i As Integer = 0 To 19
                ds.Tables(0).Rows(i).Item("DeviceID") = FileName
            Next
            ds.WriteXml(App_Dir & FileName & ".XML")
        End Try
        Return ds
    End Function

End Module
